/* eslint-disable no-undef,no-throw-literal */
import axios from 'axios';

axios.defaults.baseURL = location.origin + '/api/';
axios.defaults.timeout = 10000;
window.axios = axios;

axios.interceptors.request.use(function (configure) {
	let token = __.$storage.get(__.$key.ACCESS_TOKEN);
	if (token !== null) {
		configure.headers['Authorization'] = 'Bearer ' + (__.$storage.get(__.$key.ACCESS_TOKEN) || '');
	}
	return configure;
}, function (error) {
	return Promise.reject(error);
});

axios.interceptors.response.use((response) => {
	if (response.data.code === -10000) {
		$.each(response.data.data, (key, data) => {
			data.forEach(message => {
				__.$notify.error(message);
			});
		});
		throw '数据验证错误';
	}
	return response;
}, (error) => {
	switch (error.response.status) {
		case 403:
			__.$notify.error('无法获取数据, 未授权操作' + error.response.statusText);
			break;
		case 401:
			__.$notify.error(error.response.statusText);
			__.$storage.clear();
			__.$router.push({name: 'Index'});
			break;
		case 504:
		case 500:
		case 404:
		case 400:
			__.$notify.error(`链接失败: ${error.response.status} ${error.response.statusText}`);
			break;
	}
	return Promise.reject(error);
});
